package com.matriq.cloudmanager;

import java.io.FileNotFoundException;
import java.net.InetAddress;
import java.util.List;

import org.apache.http.conn.util.InetAddressUtils;

import com.matriq.cloudmanager.R;
import com.matriq.cloudmanager.entity.TeachPlan;
import com.matriq.cloudmanager.service.AccountService;
import com.sangfor.ssl.IVpnDelegate;
import com.sangfor.ssl.SFException;
import com.sangfor.ssl.SangforAuth;
import com.sangfor.ssl.common.VpnCommon;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import net.lgpage.http.ExceptionAsyncTask;
import net.lgpage.util.CrashHandler;
import net.lgpage.util.PromptTool.TagTool;
import net.lgpage.util.PromptTool.ToastUtil;

public class MainActivity2 extends Activity  implements IVpnDelegate{
	 private static  final  String TAG=MainActivity2.class.getSimpleName();
	private static final String VPN_IP = "125.214.113.102";
	private static final int VPN_PORT = 443;
	private static final String USER = "cs";
	private static final String PASSWD = "111111";
	private InetAddress m_iAddr;
	private SangforAuth sfAuth = null;
	private ProgressDialog progress;
	View v;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_main);
		View v = findViewById(R.id.root);
	
		Thread.setDefaultUncaughtExceptionHandler(CrashHandler.getInstance());
		try {
			com.sangfor.ssl.service.utils.logger.Log
					.init(getApplicationContext());
			com.sangfor.ssl.service.utils.logger.Log.LEVEL = com.sangfor.ssl.service.utils.logger.Log.DEBUG;
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		sfAuth = SangforAuth.getInstance();
		// sfAuth.init(this, this, SangforAuth.AUTH_MODULE_EASYAPP);
			try {
				sfAuth.init(this, this, SangforAuth.AUTH_MODULE_EASYAPP);
				sfAuth.setLoginParam("10"/* AUTH_CONNECT_TIME_OUT */,
						String.valueOf(5));
				initSslVpn();
			} catch (Exception e) {
				e.printStackTrace();
			}
		v.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ExceptionAsyncTask<List<TeachPlan> > task = new ExceptionAsyncTask<List<TeachPlan> >(
						MainActivity2.this) {

					@Override
					public void onPostExecuteX(List<TeachPlan> result) {
						TagTool.e("haha", result.toString());
						ToastUtil.noretryToast(MainActivity2.this, result.toString());
					}

					@Override
					public List<TeachPlan>  doInBackgroundX(String... String)
							throws Exception {
						return AccountService.getService().teach_plan();
					}
				};

				task.execute();
			}
		});
	}
	 /**
     * 开始初始化VPN，该初始化为异步接口，后续动作通过回调函数通知结果
     *
     * @return 成功返回true，失败返回false，一般情况下返回true
     */
    private boolean initSslVpn()  {
        progress=ProgressDialog.show(MainActivity2.this,"","VPN连接中...",true,false);
        SangforAuth sfAuth = SangforAuth.getInstance();

        if(!InetAddressUtils.isIPv4Address(VPN_IP)){
        	ToastUtil.noretryToast(this, "vpn ipaddress invalid");
            return false;
        }
        long host = VpnCommon.ipToLong(VPN_IP);
        int port = VPN_PORT;

        if (sfAuth.vpnInit(host, port) == false) {
            Log.d(TAG, "vpn init fail, errno is " + sfAuth.vpnGeterr());
            return false;
        }

        return true;
    }
    /**
     * 处理认证，通过传入认证类型（需要的话可以改变该接口传入一个hashmap的参数用户传入认证参数）.
     * 也可以一次性把认证参数设入，这样就如果认证参数全满足的话就可以一次性认证通过，可见下面屏蔽代码
     *
     * @param authType
     *            认证类型
     * @throws SFException
     */
    private void doVpnLogin(int authType) {
        Log.d(TAG, "doVpnLogin authType " + authType);

        boolean ret = false;
        SangforAuth sfAuth = SangforAuth.getInstance();

        switch (authType) {
            case IVpnDelegate.AUTH_TYPE_CERTIFICATE:

                break;
            case IVpnDelegate.AUTH_TYPE_PASSWORD:
                sfAuth.setLoginParam(IVpnDelegate.PASSWORD_AUTH_USERNAME,USER);
                sfAuth.setLoginParam(IVpnDelegate.PASSWORD_AUTH_PASSWORD, PASSWD);
                sfAuth.setLoginParam(IVpnDelegate.SET_RND_CODE_STR, "");
                ret = sfAuth.vpnLogin(IVpnDelegate.AUTH_TYPE_PASSWORD);
                break;
            case IVpnDelegate.AUTH_TYPE_SMS:
                sfAuth.setLoginParam(IVpnDelegate.SMS_AUTH_CODE, "");
                ret = sfAuth.vpnLogin(IVpnDelegate.AUTH_TYPE_SMS);
                break;
            case IVpnDelegate.AUTH_TYPE_SMS1:
                ret = sfAuth.vpnLogin(IVpnDelegate.AUTH_TYPE_SMS1);
                break;
            default:
                Log.w(TAG, "default authType " + authType);
                break;
        }

        if (ret == true) {
            Log.i(TAG, "success to call login method");
        } else {
            Log.i(TAG, "fail to call login method");
        }

    }

    @Override
    public void vpnCallback(int vpnResult, int authType) {
        SangforAuth sfAuth = SangforAuth.getInstance();

        switch (vpnResult) {
            case IVpnDelegate.RESULT_VPN_INIT_FAIL:

                /**
                 * 初始化vpn失败
                 */
                Log.i(TAG, "RESULT_VPN_INIT_FAIL, error is " + sfAuth.vpnGeterr());
                displayToast("VPN初始化失败," + sfAuth.vpnGeterr());
                if(progress!=null){
                    progress.hide();
                    progress=null;
                }
                break;

            case IVpnDelegate.RESULT_VPN_INIT_SUCCESS:
                /**
                 * 初始化vpn成功，接下来就需要开始认证工作了
                 */

                Log.i(TAG,
                        "RESULT_VPN_INIT_SUCCESS, current vpn status is " + sfAuth.vpnQueryStatus());
                //displayToast("RESULT_VPN_INIT_SUCCESS, current vpn status is "
                //        + sfAuth.vpnQueryStatus());
                Log.i(TAG, "vpnResult===================" + vpnResult  + "\nauthType ==================" + authType);
                // 初始化成功，进行认证操作
                doVpnLogin(IVpnDelegate.AUTH_TYPE_PASSWORD);
//				doVpnLogin(IVpnDelegate.AUTH_TYPE_CERTIFICATE)
//				doVpnLogin(authType);
//				String hardidString = sfAuth.vpnQueryHardID();
//				Log.w(TAG, "vpn hardid ============================ " + hardidString);
                break;

            case IVpnDelegate.RESULT_VPN_AUTH_FAIL:
                /**
                 * 认证失败，有可能是传入参数有误，具体信息可通过sfAuth.vpnGeterr()获取
                 */
                String errString = sfAuth.vpnGeterr();
                Log.i(TAG, "RESULT_VPN_AUTH_FAIL, error is " + sfAuth.vpnGeterr());
                displayToast("VPN认证失败," + sfAuth.vpnGeterr());
                if(progress!=null){
                    progress.hide();
                    progress=null;
                }
                break;

            case IVpnDelegate.RESULT_VPN_AUTH_SUCCESS:
                /**
                 * 认证成功，认证成功有两种情况，一种是认证通过，可以使用sslvpn功能了，另一种是前一个认证（如：用户名密码认证）通过，
                 * 但需要继续认证（如：需要继续证书认证）
                 */

                if (authType == IVpnDelegate.AUTH_TYPE_NONE) {
                    Log.i(TAG, "welcom to sangfor sslvpn!");
                    ToastUtil.noretryToast(this, "VPN连接成功");
                    if(progress!=null){
                        progress.hide();
                        progress=null;
                    }
                    // 若为L3vpn流程，认证成功后开启自动开启l3vpn服务
                    if (SangforAuth.getInstance().getModuleUsed() == SangforAuth.AUTH_MODULE_EASYAPP) {
                        // EasyApp流程，认证流程结束，可访问资源。
                        //doResourceRequest();
                    }

                } else {
                    Log.i(TAG, "auth success, and need next auth, next auth type is " + authType);
                    //displayToast("auth success, and need next auth, next auth type is " + authType);

                    if (authType == IVpnDelegate.AUTH_TYPE_SMS) {
                        // 输入短信验证码
                        displayToast("you need send sms code.");
                    } else {
                        doVpnLogin(authType);
                    }
                }
                break;
            case IVpnDelegate.RESULT_VPN_AUTH_CANCEL:
                Log.i(TAG, "RESULT_VPN_AUTH_CANCEL");
                displayToast("RESULT_VPN_AUTH_CANCEL");
                break;
            case IVpnDelegate.RESULT_VPN_AUTH_LOGOUT:
                /**
                 * 主动注销（自己主动调用logout接口）或者被动注销（通过控制台把用户踢掉）均会调用该接口
                 */

                //tunObserver.stopWatching();
                Log.i(TAG, "RESULT_VPN_AUTH_LOGOUT");
                displayToast("RESULT_VPN_AUTH_LOGOUT");
                break;
            case IVpnDelegate.RESULT_VPN_L3VPN_FAIL:
                /**
                 * L3vpn启动失败，有可能是没有l3vpn资源，具体信息可通过sfAuth.vpnGeterr()获取
                 */
                Log.i(TAG, "RESULT_VPN_L3VPN_FAIL, error is " + sfAuth.vpnGeterr());
                displayToast("RESULT_VPN_L3VPN_FAIL, error is " + sfAuth.vpnGeterr());
                break;
            case IVpnDelegate.RESULT_VPN_L3VPN_SUCCESS:
                /**
                 * L3vpn启动成功

                 //				registerNetWorkBroadcasts(); //注册网络监听广播
                 if (tunObserver == null) {
                 tunObserver = new TunObserver();
                 }
                 Log.i(TAG, "start tun0 observe");
                 tunObserver.startWatching();
                 Log.i(TAG, "RESULT_VPN_L3VPN_SUCCESS ===== " + SystemConfiguration.getInstance().getSessionId());
                 displayToast("RESULT_VPN_L3VPN_SUCCESS");
                 // L3vpn流程，认证流程结束，可访问资源。
                 doResourceRequest();*/

                break;
            case IVpnDelegate.VPN_STATUS_ONLINE:
                /**
                 * 与设备连接建立
                 */
                Log.i(TAG, "vpn online");
                //displayToast("online");
                break;
            case IVpnDelegate.VPN_STATUS_OFFLINE:
                /**
                 * 与设备连接断开
                 */
                Log.i(TAG, "offline");
                displayToast("offline");
                break;
            default:
                /**
                 * 其它情况，不会发生，如果到该分支说明代码逻辑有误
                 */
                Log.i(TAG, "default result, vpn result is " + vpnResult);
                //displayToast("default result, vpn result is " + vpnResult);
                break;
        }
    }

    @Override
    public void reloginCallback(int status, int result) {
        switch (status){

            case IVpnDelegate.VPN_START_RELOGIN:
                Log.e(TAG, "relogin callback start relogin start ...");
                break;
            case IVpnDelegate.VPN_END_RELOGIN:
                Log.e(TAG, "relogin callback end relogin ...");
                if (result == IVpnDelegate.VPN_RELOGIN_SUCCESS){
                    Log.e(TAG, "relogin callback, relogin success!");
                } else {
                    Log.e(TAG, "relogin callback, relogin failed");
                }
                break;
        }
    }

    @Override
    public void vpnRndCodeCallback(byte[] data) {
        Log.d(TAG, "vpnRndCodeCallback data: " + Boolean.toString(data==null));
        /*if (data != null) {
            Drawable drawable = Drawable.createFromStream(new ByteArrayInputStream(data),
                    "rand_code");
            imgbtn_rnd_code.setBackgroundDrawable(drawable);
        }*/
    }

    private void displayToast(String str) {
        Toast.makeText(getApplicationContext(), str,Toast.LENGTH_SHORT).show();
    }
}
